<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="物料群组管理"
      :columns="columns"
      :request-api="getMaterialGroupList"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
        <el-button type="success" :disabled="!scope.isSelected" @click="handleBatchEnable(scope.selectedListIds)">
          批量启用
        </el-button>
        <el-button type="warning" :disabled="!scope.isSelected" @click="handleBatchDisable(scope.selectedListIds)">
          批量禁用
        </el-button>
        <el-button :icon="Download" @click="handleExport">导出</el-button>
      </template>

      <!-- 分组类型 -->
      <template #groupType="scope">
        <el-tag v-if="scope.row.groupType" type="info" size="small">
          {{ getGroupTypeLabel(scope.row.groupType) }}
        </el-tag>
        <span v-else>-</span>
      </template>

      <!-- 物料数量 -->
      <template #materialCount="scope">
        <div style="display: flex; align-items: center; justify-content: center; gap: 8px">
          <el-icon color="#67C23A"><Box /></el-icon>
          <span style="font-weight: 600; color: #67c23a">{{ scope.row.materialCount || 0 }}</span>
        </div>
      </template>

      <!-- 状态 -->
      <template #status="scope">
        <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'warning'">
          {{ scope.row.status === "ACTIVE" ? "启用" : "禁用" }}
        </el-tag>
      </template>

      <!-- 创建时间 -->
      <template #createdTime="scope">
        <span>{{ formatDateTime(scope.row.createdTime) }}</span>
      </template>

      <!-- 操作 -->
      <template #operation="scope">
        <el-button type="primary" link @click="handleViewInDrawer(scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'" link @click="handleStatusToggle(scope.row)">
          {{ scope.row.status === "ACTIVE" ? "禁用" : "启用" }}
        </el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </ProTable>

    <!-- 表单抽屉 -->
    <MaterialGroupDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="materialGroup">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, Delete, Box, Download } from "@element-plus/icons-vue";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import MaterialGroupDrawer from "./form.vue";
import {
  getMaterialGroupList,
  createMaterialGroup,
  updateMaterialGroup,
  deleteMaterialGroup,
  enableMaterialGroup,
  disableMaterialGroup,
  type MaterialGroup
} from "@/api/modules/materialGroup";

// ProTable 实例
const proTable = ref();

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 获取群组类型标签
const getGroupTypeLabel = (groupType: string) => {
  const typeMap: Record<string, string> = {
    MATERIAL_TYPE: "按物料类型",
    PROCESS_ATTR: "按工艺属性",
    BUSINESS_ATTR: "按业务属性",
    PRICING_METHOD: "按计价方式"
  };
  return typeMap[groupType] || groupType;
};

// 群组类型选项
const groupTypeOptions = [
  { label: "按物料类型", value: "MATERIAL_TYPE" },
  { label: "按工艺属性", value: "PROCESS_ATTR" },
  { label: "按业务属性", value: "BUSINESS_ATTR" },
  { label: "按计价方式", value: "PRICING_METHOD" }
];

// 状态选项
const statusOptions = [
  { label: "启用", value: "ACTIVE" },
  { label: "禁用", value: "INACTIVE" }
];

// 表格配置项
const columns: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 50 },
  { type: "index", label: "#", width: 80 },
  {
    prop: "groupCode",
    label: "群组编码",
    width: 120,
    search: { el: "input", props: { placeholder: "请输入群组编码" } }
  },
  {
    prop: "groupName",
    label: "群组名称",
    width: 150,
    search: { el: "input", props: { placeholder: "请输入群组名称" } }
  },
  {
    prop: "groupType",
    label: "分组类型",
    width: 120,
    search: {
      el: "select",
      props: { placeholder: "请选择分组类型" }
    },
    enum: groupTypeOptions
  },
  {
    prop: "materialCount",
    label: "物料数量",
    width: 120,
    align: "center"
  },
  {
    prop: "status",
    label: "状态",
    width: 80,
    search: {
      el: "select",
      props: { placeholder: "请选择状态" }
    },
    enum: statusOptions
  },
  {
    prop: "description",
    label: "描述",
    minWidth: 150,
    showOverflowTooltip: true
  },
  {
    prop: "createdTime",
    label: "创建时间",
    width: 160
  },
  {
    prop: "operation",
    label: "操作",
    width: 320,
    fixed: "right"
  }
];

// 初始化参数
const initParam = reactive({});

// 数据回调处理
const dataCallback = (data: any) => {
  return {
    list: data.records || [],
    total: Number(data.total) || 0  // 确保 total 是数字类型
  };
};

// 表单抽屉引用
const drawerRef = ref<InstanceType<typeof MaterialGroupDrawer>>();

// 获取表格数据列表
const getTableList = () => {
  proTable.value?.getTableList();
};

// 新增
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    api: addMaterialGroup,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑
const handleEdit = (row: MaterialGroup.MaterialGroupListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    api: editMaterialGroup,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 查看
const handleViewInDrawer = (row: MaterialGroup.MaterialGroupListItem) => {
  const params = {
    title: "查看",
    isView: true,
    row: { ...row },
    api: undefined,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 新增物料群组
const addMaterialGroup = async (params: MaterialGroup.CreateMaterialGroupRequest) => {
  return await createMaterialGroup(params);
};

// 编辑物料群组
const editMaterialGroup = async (params: MaterialGroup.MaterialGroupListItem) => {
  return await updateMaterialGroup(params.id, params);
};

// 删除
const handleDelete = async (row: MaterialGroup.MaterialGroupListItem) => {
  try {
    // 检查是否有关联物料
    if (row.materialCount && row.materialCount > 0) {
      ElMessage.warning("该群组下存在物料，无法删除");
      return;
    }

    await ElMessageBox.confirm(`确认删除物料群组 "${row.groupName}" 吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      message: `<p>删除后将无法恢复，请谨慎操作！</p><p>群组编码：${row.groupCode}</p><p>群组名称：${row.groupName}</p>`
    });

    await deleteMaterialGroup(row.id);
    ElMessage.success("删除成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 启用/禁用状态切换
const handleStatusToggle = async (row: MaterialGroup.MaterialGroupListItem) => {
  try {
    const action = row.status === "ACTIVE" ? "禁用" : "启用";
    await ElMessageBox.confirm(`确认${action}物料群组 "${row.groupName}" 吗？`, `${action}确认`, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    if (row.status === "ACTIVE") {
      await disableMaterialGroup(row.id);
    } else {
      await enableMaterialGroup(row.id);
    }

    ElMessage.success(`${action}成功`);
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 批量启用
const handleBatchEnable = async (ids: string[]) => {
  if (!ids.length) {
    ElMessage.warning("请选择要启用的物料群组");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认启用选中的 ${ids.length} 个物料群组吗？`, "批量启用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = ids.map(id => enableMaterialGroup(id));
    await Promise.all(promises);
    ElMessage.success("批量启用成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量启用失败");
    }
  }
};

// 批量禁用
const handleBatchDisable = async (ids: string[]) => {
  if (!ids.length) {
    ElMessage.warning("请选择要禁用的物料群组");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认禁用选中的 ${ids.length} 个物料群组吗？`, "批量禁用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = ids.map(id => disableMaterialGroup(id));
    await Promise.all(promises);
    ElMessage.success("批量禁用成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量禁用失败");
    }
  }
};

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info("正在导出数据...");
    // 这里可以调用导出API
    // const searchParam = proTable.value?.searchParam;
    // await exportMaterialGroupList(searchParam);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};
</script>

<style scoped>
</style>